import { login } from '../api';

export default {

  state: {
    userInfo: null
  },

  getters: {
    userInfo: state => state.userInfo
  },

  mutations: {
    setUserInfo(state, user) {
      state.userInfo = user;
      localStorage.setItem('elementUser', JSON.stringify(user));
    }
  },

  actions: {

    /**
     * 登录接口
     * @param data 提交到接口的数据
     * **/
    handleLogin({ commit }, data) {
      return new Promise((resolve, reject) => {
        login(data).then(res => {
          //登录成功业务逻辑
          const { code, data } = res;
          if (code === 200) {
            commit('setUserInfo', data);
            localStorage.setItem('elementUser', JSON.stringify(data));
          }
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },

    /**
     * 退出
     * **/
    handleLogout({ commit }) {
      commit('setUserInfo', "");
      localStorage.removeItem('userInfo');
    }

  }
};
